package org.crag.cafca.gui.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.crag.cafca.db.SqlConnector;
import org.crag.cafca.logic.time.Source;
import org.crag.cafca.logic.time.TimeLine;
import org.crag.cafca.logic.time.TimeLineManager;
import org.crag.cafca.util.Utilities;
import org.joda.time.DateTime;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 * Retrieve items from the DB to populate the ComboBox in addSourceForm.jsp.
 */
@WebServlet("/SourceServlet")
public class SourceServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public SourceServlet() {
        super();
    }
	
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		HttpSession session = request.getSession(); 
		String username = (String) session.getAttribute("username"); 
						
		TimeLine timeline = (TimeLine) session.getAttribute("timeline");
		TimeLineManager manager=new TimeLineManager();
		
		Map<String, Source> sources = manager.getSources(null,timeline);
				
		JSONObject toSendBack = new JSONObject(); 
		JSONArray dataArray = new JSONArray();
		
		for(String item : sources.keySet())
		{
			JSONObject row = new JSONObject(); 
			row.put("sourceId", item);
			dataArray.put(row); 
		}
		
		toSendBack.put("data", dataArray); 
		toSendBack.put("success", true); 
		response.getWriter().print(toSendBack.toString());
		response.setStatus(HttpServletResponse.SC_OK);
	}

}
